package com.donnie.shopping.service.impl;

import com.donnie.shopping.config.FruitConfig;
import com.donnie.shopping.entity.vo.FruitOrderItem;
import com.donnie.shopping.enums.Fruit;
import com.donnie.shopping.service.ICalculationStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Map;

/**
 * @description: 折扣计价策略
 * @author: ChenDeXin
 * @time: 2025/5/20 10:39
 */
@Slf4j
@Service("discountCalculator")
public class DiscountCalculator implements ICalculationStrategy {
    @Resource
    FruitConfig fruitConfig;

    /**
     * 计算费用 <br>
     *
     * @param orderItems
     * @return java.lang.Double <br>
     * @date: 2025/5/20 10:16 <br>
     * @author: ChenDeXin <br>
     */
    @Override
    public Double calculate(List<FruitOrderItem> orderItems) {
        //扩展 - 各种水果都有可能出现折扣，目前为草莓打8折
        Map<String, Double> discountMap = fruitConfig.getDiscountList();

        return orderItems.stream().mapToDouble(item -> {
                    Fruit fruit = item.getFruit();
                    Double discount = discountMap.get(fruit.name());

                    Double currentPriceAmt = new BigDecimal(item.getCurrentPriceAmt())
                            .setScale(3, RoundingMode.HALF_UP).doubleValue();

                    Double disCountPriceAmt = new BigDecimal(currentPriceAmt * discount)
                            .setScale(3, RoundingMode.HALF_UP).doubleValue();

                    log.info("当前水果：{}，单价：{}，优惠价：{}, 购买量：{}，总价：{}，优惠后总价：{}",
                            fruit.name(), fruit.getPrice(), fruit.getPrice() * discount,
                            item.getQuantity(), currentPriceAmt,
                            disCountPriceAmt);

                    return disCountPriceAmt;
                })
                .sum();
    }
}
